package com.firemoss.atonement.entitymanager.util
{
	import com.firemoss.atonement.entitymanager.EntityManager;
	import com.firemoss.atonement.metadata.AtonementMetadata;
	import com.firemoss.atonement.metadata.EntityMetadata;
	
	import org.as3commons.reflect.Type;

	public class IdUtil
	{
		
		public static function getIdValue( entity : Object, entityManager : EntityManager, entityClazz : Class = null) : *
		{
			var md : AtonementMetadata
			var emd : EntityMetadata
			
			if ( entityClazz )
			{
				md = entityManager.metadataBuilder.buildMetadataForClass( entityClazz )
				
				if ( md.entityMetadata && entity.hasOwnProperty( md.entityMetadata.idPropertyName ) )
				{
					return entity[ md.entityMetadata.idPropertyName ];
				}
			}
			
			emd = entityManager.getEntityMetadata( entity )
				
			if ( !emd )
			{
				throw new Error( "Can't determine entity metadata for an object of type " + Type.forInstance( entity ).fullName );
			}
			
			return entity[ emd.idPropertyName ];
		}
		public static function setIdValue( entity : Object, value : *, entityManager : EntityManager ) : void
		{
			var emd : EntityMetadata = entityManager.getEntityMetadata( entity )
			
			entity[ emd.idPropertyName ] = value;
		}
	}
}